import { reqAddClass, reqUpdateClass } from "@/api/reqClass";
import type { ClassForm } from "@/types/class";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { reactive, ref, type Ref } from "vue";

export const useAUClass = (changeRef: Ref<boolean>) => {
  const titleRef = ref("");
  const dialogRef = ref(false);
  const close = () => {
    // 1. 表单数据初始化
    classForm.value = {
      classname: "",
      manager_id: "",
      teacher_id: "",
    };
    classEle.value?.resetFields();
    // 2. 关闭弹窗
    dialogRef.value = false;
  };

  //   定义班级数据对象
  const classForm = ref<ClassForm>({
    classname: "",
    manager_id: "",
    teacher_id: "",
  });

  //  定义表单校验对象
  const formRules = reactive<FormRules<ClassForm>>({
    classname: [
      {
        required: true,
        message: "请添加班级名称",
        trigger: "blur",
      },
    ],
    teacher_id: [
      {
        required: true,
        message: "选择授课老师",
        trigger: "change",
      },
    ],
    manager_id: [
      {
        required: true,
        message: "选择学管老师",
        trigger: "change",
      },
    ],
  });

  const classEle = ref<FormInstance>();
  const addClassHandler = () => {
    titleRef.value = "添加班级";
    dialogRef.value = true;
  };

  
  const addClass = async () => {
    // 发送请求，进行表单验证
    // classEle.value?.validate((isOK) => {})
    await classEle.value?.validate();
    // 发送添加班级的请求
    const { status, msg } = await reqAddClass(classForm.value);
    if (status == 0) {
      return "添加成功";
    } else {
      return Promise.reject(msg);
    }
  };

  const updateClassHandler = (val: ClassForm) => {
    titleRef.value = "修改班级";
    dialogRef.value = true;
    // 记录当前展示的对象
    classForm.value = {
      ...val,
    };
  };

  const updateClass = async () => {
    await classEle.value?.validate();
    const { status, msg } = await reqUpdateClass(classForm.value);
    if (status === 0) {
      return "修改成功";
    } else {
      return Promise.reject(msg);
    }
  };

  const addOrUpdate = async () => {
    try {
      let msg: string | undefined = "";
      if (titleRef.value === "添加班级") {
        msg = await addClass();
      } else {
        msg = await updateClass();
      }
      changeRef.value = !changeRef.value;
      close();
      // 重新拉取数据
      ElMessage.success(msg);
    } catch (error) {
      if (typeof error === "string") {
        ElMessage.error(error);
      }
      // console.log(error)
    }
  };
  return {
    titleRef,
    dialogRef,
    classForm,
    formRules,
    classEle,
    addClass,
    close,
    addClassHandler,
    updateClassHandler,
    addOrUpdate,
  };
};
